//
//  MDMusementHeadView.swift
//  麦兜直播
//
//  Created by Apple on 16/10/21.
//  Copyright © 2016年 yeqingyu. All rights reserved.
//

import UIKit
private let musementHeadViewID = "MDMusementHeadView"

class MDMusementHeadView: UIView {
    var musmes:[MDHomeGroup]?{
        didSet{
            collectionView.reloadData()
        }
    }

    @IBOutlet weak var layout: UICollectionViewFlowLayout!
    @IBOutlet weak var collectionView: UICollectionView!
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // 设置该控件不随着父控件的拉伸而拉伸
        autoresizingMask = UIViewAutoresizing()
        
        collectionView.register(UINib(nibName: "MDMusementCell", bundle: nil), forCellWithReuseIdentifier: musementHeadViewID)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        layout.itemSize = bounds.size
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
    }
   
    class func show() -> MDMusementHeadView {
        
        return  Bundle.main.loadNibNamed("MDMusementHeadView", owner: nil, options: nil)?.first as! MDMusementHeadView
    }
}
// MARK:- 数据源方法
extension MDMusementHeadView:UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if musmes==nil {
            return 0
        }
        let pageNum = ((musmes?.count)! - 1) / 8 + 1
    
        
        return pageNum
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: musementHeadViewID, for: indexPath)
        setupCellDataWithCell(cell: cell as! MDMusementCell, indexPath: indexPath)
        return cell
    }
    
    private func setupCellDataWithCell(cell : MDMusementCell, indexPath : IndexPath) {
        // 0页: 0 ~ 7
        // 1页: 8 ~ 15
        // 2也: 16 ~ 23
        // 1.取出起始位置&终点位置
        let startIndex = indexPath.item * 8
        var endIndex = (indexPath.item + 1) * 8 - 1
        
        // 2.判断越界问题
        if endIndex > musmes!.count - 1 {
            endIndex = musmes!.count - 1
        }
        
        // 3.取出数据,并且赋值给cell
        cell.datas = Array(musmes![startIndex...endIndex])
    }
}
